#!/usr/bin/env python
#
import os
import re
import datetime
import time
from google.appengine.ext.webapp import template
import webapp2 as webapp

_DEBUG = True
__author__ = 'Nerijus Terebas'

class MainHandler(webapp.RequestHandler):

  def get(self):
    greeting = ''
    bio_cgi_url = "/bioview"
    gimmet=''
    gimmen=''
    gimdien=''
    simbsafe  = re.compile("[^0-9a-zA-Z]")
    mazosios  = re.compile("[^a-z]")
    skaic  = re.compile("[^0-9]")
    handler = {}
    if 'HTTP_COOKIE' in os.environ:
      cookies = os.environ['HTTP_COOKIE']
      cookies = cookies.split('; ')
      for cookie in cookies:
        cookie = cookie.split('=')
        handler[cookie[0]] = cookie[1]
    if 'terebasGimd' in handler:
      gimd = handler['terebasGimd']
      gimd = str(skaic.sub("", gimd))
      try:
        gimmet=gimd[0,4]
        gimmen=gimd[4,6]
        gimdien=gimd[6,8]
      except:
        zerr = True
    unixtime=time.time()
    d = datetime.datetime.fromtimestamp(unixtime)
    lang = self.request.get('lang') or 'lt'
    gimmet = self.request.get('gmet') or gimmet
    gimmen = self.request.get('gmem') or gimmen
    gimdien = self.request.get('gdien') or gimdien
    siemet = self.request.get('smet') or d.strftime('%Y')
    men = self.request.get('men') or d.strftime('%m')
    biohtml=''
    if not lang:
      lang = 'lt'
    else:
      lang = mazosios.sub("", lang)
    if not gimmet:
      gimmet = '1970'
    else:
      gimmet = skaic.sub("", gimmet)
    if not gimmen:
      gimmen = '06'
    else:
      gimmen = skaic.sub("", gimmen)
    if not gimdien:
      gimdien = '20'
    else:
      gimdien = skaic.sub("", gimdien)
    if not siemet:
      format = '%Y'
      siemet = d.strftime(format)
    else:
      siemet = skaic.sub("", siemet)
    if not men:
      format = '%m'
      men = d.strftime(format)
    else:
      men = skaic.sub("", men)
    if self.request.get('gmet') and self.request.get('gmem') and self.request.get('gdien'):
      bioduom = "lang="+lang+"&gmet="+gimmet+"&gmem="+gimmen+"&gdien="+gimdien+"&smet="+siemet+"&men="+men
      biohtml = "<img src=\""+bio_cgi_url+"?"+bioduom+"\" height=\"256\" width=\"256\" alt=\"\">\n"
    template_values2 = {
      'biohtml': biohtml,
      'gimmet': gimmet,
      'gimmen': gimmen,
      'gimdien': gimdien,
      'siemet': siemet,
      'men': men
    }
    directory = os.path.dirname(__file__)
    path = os.path.join(directory,  "bio.html")
    cont1 = template.render(path, template_values2, debug=_DEBUG)
    self.response.out.write(cont1)
 


#def main():
app = webapp.WSGIApplication([('/biorhythm', MainHandler),('/', MainHandler)],
                                     debug=True)
#  run_wsgi_app(application)


#if __name__ == '__main__':
#  main()


